package com.example.queryexpressdelivery_01.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.queryexpressdelivery_01.common.DeliveryDAL;
import com.example.queryexpressdelivery_01.common.HttpGetData;
import com.example.queryexpressdelivery_01.adapter.IndexRvAdapter;
import com.example.queryexpressdelivery_01.R;
import com.example.queryexpressdelivery_01.activity.LoginActivity;
import com.example.queryexpressdelivery_01.entity.FeedbackData;
import com.example.queryexpressdelivery_01.entity.UserData;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OtherFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OtherFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private String sTitle;
    private String userid;
    private EditText edtOtherNumber;
    private AutoCompleteTextView actvOtherFeedBack;
    private Button btnOtherNumber;
    private Button btnOtherFeedBack;
    private Button btnOtherLogOut;
    private ImageView tvOtherInfo;
    private HttpGetData httpGetData;
    private DeliveryDAL deliveryDAL;
    private Gson gson=new Gson();
    private IndexRvAdapter indexRvAdapter = new IndexRvAdapter();
    public OtherFragment() {
        // Required empty public constructor
    }

    public OtherFragment(String sTitle, String userid) {
        this.sTitle = sTitle;
        this.userid = userid;
        Bundle d1 = new Bundle();
        d1.putString("param1", sTitle);
        d1.putString("id", userid);
        this.setArguments(d1);
    }

    public String getTitle() {
        return sTitle;
    }

    public String getUserid() {
        return userid;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment OtherFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OtherFragment newInstance(String param1, String param2) {
        OtherFragment fragment = new OtherFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    public void onStart() {
        super.onStart();
        btnOtherLogOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), LoginActivity.class));
            }
        });
        btnOtherNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deliveryDAL =new DeliveryDAL(getContext());
                String number = edtOtherNumber.getText().toString().trim();
                UserData userData = deliveryDAL.queryById(Integer.parseInt(userid));
                if (!number.isEmpty()){
                    LayoutInflater inflater = LayoutInflater.from(getContext());
                    View dialogView = inflater.inflate(R.layout.dialog_other, null);
                    httpGetData = new HttpGetData(number,null,userData.getPhone());
                    new AlertDialog.Builder(getContext()).setView(dialogView).setTitle("误触提示！")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    String result = httpGetData.Unknown();
                                    if (result!=null)Toast.makeText(getContext(),"提交成功，感谢您的提交！",Toast.LENGTH_SHORT).show();
                                    else Toast.makeText(getContext(),"提交失败，发送未知错误！",Toast.LENGTH_SHORT).show();
                                    FeedbackData feedbackData = gson.fromJson(userData.getData(), FeedbackData.class);
                                    if (feedbackData!=null){
                                        feedbackData.setNumberfeedback(number);
                                    }else {
                                        feedbackData = new FeedbackData();
                                        feedbackData.setNumberfeedback(number);
                                    }
                                    String json = gson.toJson(feedbackData);
                                    userData.setData(json);
                                    deliveryDAL.updateUser(userData);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            })
                    .create().show();
                }else Toast.makeText(getContext(),"输入不能为空",Toast.LENGTH_SHORT).show();
            }
        });
        btnOtherFeedBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deliveryDAL =new DeliveryDAL(getContext());
                String feedback = actvOtherFeedBack.getText().toString().trim();
                UserData userData = deliveryDAL.queryById(Integer.parseInt(userid));
                if (!feedback.isEmpty()){
                    LayoutInflater inflater = LayoutInflater.from(getContext());
                    View dialogView = inflater.inflate(R.layout.dialog_other, null);
                    new AlertDialog.Builder(getContext()).setView(dialogView).setTitle("误触提示！")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Toast.makeText(getContext(),"提交成功，感谢您的提交！",Toast.LENGTH_SHORT).show();
                                    FeedbackData feedbackData = gson.fromJson(userData.getData(), FeedbackData.class);
                                    List<FeedbackData.ProblemFeedback> problemFeedbacks = feedbackData.getProblemfeedback();
                                    FeedbackData.ProblemFeedback pf = new FeedbackData.ProblemFeedback();
                                    pf.setProblem(feedback);
                                    if (problemFeedbacks==null)problemFeedbacks = new ArrayList<>();
                                    problemFeedbacks.add(pf);
                                    feedbackData.setProblemfeedback(problemFeedbacks);
                                    String json = gson.toJson(feedbackData);
                                    userData.setData(json);
                                    deliveryDAL.updateUser(userData);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            })
                            .create().show();
                }else Toast.makeText(getContext(),"输入不能为空",Toast.LENGTH_SHORT).show();
            }
        });
        tvOtherInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deliveryDAL = new DeliveryDAL(getContext());
                UserData userData = deliveryDAL.queryById(Integer.parseInt(userid));
                FeedbackData feedbackData = gson.fromJson(userData.getData(),FeedbackData.class);
                LayoutInflater inflater = LayoutInflater.from(getContext());
                View dialogView = inflater.inflate(R.layout.dialog_other_info, null);
                RecyclerView rvOtherInfo = dialogView.findViewById(R.id.rvOtherInfo);
                rvOtherInfo.setLayoutManager(new LinearLayoutManager(getContext()));
                List<Map<String, String>> expressInfo = new ArrayList<>();
                Map<String,String> number = new ArrayMap<>();
                if (feedbackData!=null){
                    if (feedbackData.getNumberfeedback()!=null){
                        number.put("上一次提交的异常单号：",feedbackData.getNumberfeedback());
                        expressInfo.add(number);
                    }

                    if (feedbackData.getProblemfeedback()!=null){
                        for (int j=0;j<feedbackData.getProblemfeedback().size();j++){
                            Map<String,String> p = new ArrayMap<>();
                            p.put("我的提问：",feedbackData.getProblemfeedback().get(j).getProblem());
                            Map<String,String> r = new ArrayMap<>();
                            r.put("回复：",feedbackData.getProblemfeedback().get(j).getRecover());
                            expressInfo.add(p);
                            expressInfo.add(r);
                        }
                    }
                }
                rvOtherInfo.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
                indexRvAdapter.setExpressList(expressInfo);
                rvOtherInfo.setAdapter(indexRvAdapter);
                AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setView(dialogView).setTitle("历史记录")
                        .setPositiveButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).create();
                alertDialog.show();
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_other, container, false);
        initView(view);
        return view;
    }

    private void initView(View v) {
        edtOtherNumber = (EditText) v.findViewById(R.id.edtOtherNumber);
        actvOtherFeedBack = (AutoCompleteTextView) v.findViewById(R.id.actvOtherFeedBack);
        btnOtherNumber = (Button) v.findViewById(R.id.btnOtherNumber);
        btnOtherFeedBack = (Button) v.findViewById(R.id.btnOtherFeedBack);
        btnOtherLogOut = (Button) v.findViewById(R.id.btnOtherLogOut);
        tvOtherInfo = (ImageView) v.findViewById(R.id.tvOtherInfo);
    }
}